package com.ximu.redeemcode.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximu.common_utlis.jwt.JwtUtil;
import com.ximu.common_utlis.result.Result;
import com.ximu.coupon.entity.Coupon;
import com.ximu.redeemcode.entity.RedeemCode;
import com.ximu.redeemcode.mapper.RedeemCodeMapper;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ximu
 * @since 2023-03-21
 */
@RestController
@RequestMapping("/redeemcode")
@Api(tags = "我的兑换码接口")
public class RedeemCodeController {

    @Autowired
    private RedeemCodeMapper redeemCodeMapper;

    @ApiOperation(value = "查询用户未使用的兑换码")
    @PostMapping("findAllRedeemCode")
    public Result findAllRedeemCode(@RequestHeader("Authorization") String token){
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();

            QueryWrapper<RedeemCode> queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", Integer.parseInt(subject));
            queryWrapper.eq("state", 0);
            List<RedeemCode> redeemCodes = redeemCodeMapper.selectList(queryWrapper);
            return Result.ok().data("redeemCodes",redeemCodes).message("成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("查询失败，检查是否登录");
    }

    @ApiOperation(value = "消费兑换码//尽量别直接调用，写支付接口会自动调用")
    @PostMapping("useRedeemCode")
    public Result useRedeemCode(@RequestHeader("Authorization") String token,int redeem_code_id){
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();

            QueryWrapper<RedeemCode> queryWrapper = new QueryWrapper();
            queryWrapper.eq("redeem_code_id", redeem_code_id);
            RedeemCode redeemCode = redeemCodeMapper.selectOne(queryWrapper);
            if (Objects.nonNull(redeemCode)){
                redeemCode.setState(1);
                int rs = redeemCodeMapper.updateById(redeemCode);
                if (rs>0){

                    return Result.ok().data("redeemCode",redeemCode).message("使用成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("使用失败");
    }

}

